require 'rubygems'
require 'blather'
require 'pp'
require 'readline'
require 'etc'


module Epic

# http://bogojoker.com/readline/
	class Cmdline
		attr_accessor :client
		LIST = [ 'say', 'discover', 'quit', 'list', 'get', 
			'epic.commands', 'epic.info', 'epic.execute', 'epic.submit' ].sort

		def initialize(client)
			@client = client
			@file = "#{Etc.getpwuid.dir}/.epic"
			setup
		end

		def setup
			comp = proc { |s| LIST.grep( /^#{Regexp.escape(s)}/ ) }
			Readline.completion_append_character = " "
			Readline.completion_proc = comp
			File.open(@file)
			IO.readlines(@file).each {|line|  Readline::HISTORY.push line.strip}
			process_standard_input
		end

		def process_standard_input
			input = Readline.readline('> ',true).strip
			execute_command input
			exit if input =~/quit/
			puts LIST if input =~ /help/
			write_to_file input
			process_standard_input
		end

		def write_to_file(line)
			File.open(@file,'a') {|f| f.puts line }
		end

		def execute_command(input)
			return if input =~ /help|quit/
			begin
				puts(@client.instance_eval input)
			rescue Exception => e
				puts e
			end
		end

	end
end
